#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import sleep
import socket
import cv2 as cv   #导入模块，opencv的python模块叫cv2
import numpy as np
import array
from PIL import ImageGrab
from mss import mss
from PIL import Image


sleep_time = 20  #20ms发送间隔
buff = bytearray(1024)
# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
send_address = ("192.168.1.131", 63333)


def socket_connect():
    # 建立连接:
    s.connect(('192.168.66.200', 80))


def socket_send(data):
    # 发送数据:
    data[0] = 0x23  #发送命令 #
    s.send(bytes(data))

def socket_send1():
    # 发送数据:
    for data in range(100000,999999):
        text = "#:%d%d%d%d%d%d%d"%(data,data,data,data,data,data,data);
        print(text)
        s.send(text.encode('utf-8'))
        sleep(0.03)


def get_image_info(image):
    #print("type:"+type(image))
    #print("size:"+image.size)
    print("width:%s"%(image.shape[0]))
    print("height:%s"%(image.shape[1]))
    print("dtype:%s"%(image.shape[2]))
    #print("array:"+np.array(image))

def get_pixel(image,x,y):
    ret = 0x00
    if (image[y + 0][x]):
        ret |= 0x01
    if (image[y + 1][x]):
        ret |= 0x02
    if (image[y + 2][x]):
        ret |= 0x04
    if (image[y + 3][x]):
        ret |= 0x08
    if (image[y + 4][x]):
        ret |= 0x10
    if (image[y + 5][x]):
        ret |= 0x20
    if (image[y + 6][x]):
        ret |= 0x40
    if (image[y + 7][x]):
        ret |= 0x80
    return ret;


def image_send_oled(img):
    x_index = 0
    y_index = 0
    gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
    gray = cv.medianBlur(gray,1)
    #gray = cv.Canny(gray, 50, 150, apertureSize = 3)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
    cv.imshow("oled", binary)
    for y in range(0,8):
        y_index = y*8
        for x in range(0, 127):
            x_index = 127*y+x
            buff[x_index] = get_pixel(binary, x, y_index)
    socket_send(buff)
    #buff[0] = 0x23
    #s.send(bytes(buff))
    
    
def desktop_oled_display1():
    with mss() as sct:
        mon = {'top': 160, 'left': 160, 'width': 200, 'height': 100}
    cv.namedWindow("video0", cv.WINDOW_AUTOSIZE)
    while(True):
        imgobj0 = sct.grab(mon)
        imgobj = Image.frombytes('RGB', (sct.width, sct.height), imgobj0)
        img = np.array(imgobj)
        cv.imshow("video0",img)
        img2 = cv.resize(img, (int(128), int(64)))
        #img = cv.resize(frame, img2, dsize);
        image_send_oled(img2)
        c= cv.waitKey(20)
        if c == 27:
            break
            
            

def desktop_oled_display():
    x=0
    y=50
    bbox = (x, y, x+512,y+256)
    cv.namedWindow("video0", cv.WINDOW_AUTOSIZE)
    while(True):
        image = ImageGrab.grab(bbox)
        img=cv.cvtColor(np.asarray(image),cv.COLOR_RGB2BGR)
        #im.save("temp.bmp",'bmp')
        #img = cv.imread("temp.bmp")
        cv.imshow("video0",img)
        img2 = cv.resize(img, (int(128), int(64)))
        #img = cv.resize(frame, img2, dsize);
        image_send_oled(img2)
        c= cv.waitKey(20)
        if c == 27:
            break


def mp4_oled_display(url):
    capture = cv.VideoCapture(url)
    print(capture.isOpened())
    cv.namedWindow("video0", cv.WINDOW_AUTOSIZE)
    while(True):
        ret ,frame = capture.read()
        if ret :
            cv.imshow("video0",frame)
            img2 = cv.resize(frame, (int(128), int(64)))
            #img = cv.resize(frame, img2, dsize);
            image_send_oled(img2)
        else:
            continue
        c= cv.waitKey(20)
        if c == 27:
            break
            

def pic_oled_display(dir,start,end):
    cv.namedWindow("image", cv.WINDOW_NORMAL)  # 创建窗口并显示的是图像类型#
    for index in range(start, end):
        url = dir+"/%03d.jpeg"%(index)
        print(url)
        img = cv.imread(url)
        cv.imshow("image",img)
        image_send_oled(img)
        cv.waitKey(20) #发送间隔


print(cv.__version__)
for i in range(1, 1024):
    buff[i] = 255
print("开始表演")
socket_connect()
#pic_oled_display("./pic",1,6578) #播放的图片路径  图片起始 结束序号
#mp4_oled_display("badapple.mp4")
desktop_oled_display()

#cv.waitKey(0)  # 等待事件触发，参数0表示永久等待
cv.destroyAllWindows()  # 释放窗口